package lyt.demo4.demos.web.dao;


import lyt.demo4.demos.web.entity.Sys_role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class Sys_roleDaolmpl implements Sys_roleDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void addRole(Sys_role role) {
        String sql = "INSERT INTO sys_role (role_name, description) VALUES (?, ?)";
        jdbcTemplate.update(sql, role.getRoleName(), role.getDescription());
    }

    @Override
    public void updateRole(Sys_role role) {
        String sql = "UPDATE sys_role SET role_name = ?, description = ? WHERE id = ?";
        jdbcTemplate.update(sql, role.getRoleName(), role.getDescription(), role.getId());
    }

    @Override
    public void deleteRole(Long id) {
        String sql = "DELETE FROM sys_role WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public Sys_role getRole(Long id) {
        String sql = "SELECT * FROM sys_role WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> {
            return new Sys_role(
                    rs.getLong("id"),
                    rs.getString("role_name"),
                    rs.getString("description")
            );
        });
    }

    @Override
    public List<Sys_role> getAllRoles() {
        String sql = "SELECT * FROM sys_role";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            return new Sys_role(
                    rs.getLong("id"),
                    rs.getString("role_name"),
                    rs.getString("description")
            );
        });
    }
}
